package com.antgroup.seckill.business.common.config;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.TimeUnit;

/**
 * @author wangxy
 * @date 2024/8/12 16:52
 */

public class RedissonClientManager {
    private static RedissonClient redissonClient;

    // 静态代码块中初始化Redisson客户端
    static {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379");
        redissonClient = Redisson.create(config);
    }


    // 获取Redisson客户端实例
    public static RedissonClient getClient() {
        return redissonClient;
    }

    // 获取锁
    public static RLock getLock(String lockKey) {
        return redissonClient.getLock(lockKey);
    }

    // 尝试获取锁
    public static boolean tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit unit) {
        RLock lock = getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 释放锁
    public static void unlock(String lockKey) {
        RLock lock = getLock(lockKey);
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }

    // 关闭Redisson客户端
    public static void shutdown() {
        redissonClient.shutdown();
    }


}
